<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>

      <el-input v-model="dataParams.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="query">查询</el-button>

    </div>

    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>

    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="buildingData">
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">

            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>

            <el-button size="mini" type="text" @click="chakan(scope.row.id)">查看</el-button>

            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.existContractFlag === 1"
              @click="editRent(scope.row.id)"
            >编辑</el-button>

            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.existContractFlag === 1"
              @click="deleteRent(scope.row.id)"
            >删除</el-button>

          </template>

        </el-table-column>

      </el-table>

    </div>
    <!-- 分页区域 -->
    <div class="block">
      <el-pagination
        :page-sizes="[5, 10, 15, 20]"
        :page-size="dataParams.pageSize"
        layout="total, prev, pager, next, sizes, jumper"
        :total="total"
        @current-change="pageChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 弹层防止的位置: 最根级的最后面 -->
    <el-dialog
      title="添加合同"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <template #default>
        <div class="form-container">
          <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
            <el-form-item label="租赁楼宇" prop="buildingId">
              <el-select v-model="rentForm.buildingId" placeholder="请选择">
                <el-option
                  v-for="item in buildingList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>

            <el-form-item label="租赁起止日期" prop="rentTime">
              <el-date-picker
                v-model="rentForm.rentTime"
                :picker-options="pickerOptions"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>

            <el-form-item label="租赁合同" prop="contractId">
              <!--action="#" 不默认上传  -->
              <el-upload
                action="#"
                :http-request="uploadContractFile"
              >
                <el-button size="small" type="primary" plain>上传合同文件</el-button>

                <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
              </el-upload></el-form-item></el-form></div></template>
      <!-- slot="footer" 过时写法 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="createRent">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>
<script>
import { getenterpriseAPI, delExterpriseAPI, getRentBuildListAPI, uploadAPI, createRentAPI } from '@/api/enterprise'

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      // 添加企业合同表单数据
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      // 企业列表查询参数
      dataParams: {
        page: 1, // 当前页码
        pageSize: 10, // 每页显示的条数
        name: '' // 搜索框中的企业名称
      },
      buildingData: [], // 存储企业数据的数组
      total: 0, // 数据总数
      title: '添加企业', // 对话框标题
      dialogVisible: false, // 控制弹层显示
      // 添加企业合同表单验证规则
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      // 渲染可租赁的楼宇列表
      buildingList: []
    }
  },
  created() {
    // 组件创建时获取企业列表
    this.getqiyeList()
    // 楼宇列表 获取 新增合同选择楼宇
    this.getRentBuildList()
  },
  methods: {
    // 创建企业合同
    async createRent() {
      const form = {
        ...this.rentForm
      }
      form.startTime = form.rentTime[0]
      form.endTime = form.rentTime[1]
      delete form.rentTime // 删除多余的字段
      // 校验表单
      const res = await createRentAPI(form)
      // console.log(res)
      if (res.code === 10000) {
        this.$message.success('添加合同成功')
      } else {
        this.$message.error('添加合同失败' + res.msg)
      }
      // 清空表单
      this.$refs.addForm.resetFields()
      this.dialogVisible = false
    },
    // 添加企业合同
    addRent(id) {
      this.rentForm.enterpriseId = id
      this.dialogVisible = true
    },
    // 上传合同文件
    async uploadContractFile(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 'contract') // 0 企业合同
      const res = await uploadAPI(formData)
      console.log(res)
      if (res.code === 10000) {
        this.rentForm.contractId = res.data.id // 更新合同id
        this.rentForm.contractUrl = res.data.url // 更新合同url
      }
    },
    // 获取未租赁的楼宇列表接口
    async getRentBuildList() {
      const res = await getRentBuildListAPI()
      console.log(res)

      this.buildingList = res.data // 更新企业数据
      this.total = res.data.total // 更新数据总数
    },
    async getqiyeList() {
      const res = await getenterpriseAPI(this.dataParams)
      this.buildingData = res.data.rows // 更新企业数据
      this.total = res.data.total // 更新数据总数
    },
    // 分页页码变化
    pageChange(page) {
      this.dataParams.page = page // 更新当前页码
      this.getqiyeList() // 重新获取企业列表
    },
    // 每页条数变化
    handleSizeChange(newSize) {
      this.dataParams.pageSize = newSize // 更新每页条数
      this.getqiyeList() // 重新获取企业列表
    },
    // 查询企业
    query() {
      this.dataParams.page = 1
      this.getqiyeList() // 重新获取企业列表
    },
    // 编辑企业
    editRent(id) {
      this.$router.push({
        path: '/exterpriseAdd',

        query: {
          id
        }
      })
    },
    // 删除合同
    deleteRent(id) {
      // 弹出确认框
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delExterpriseAPI(id)
        this.$message.success('删除成功')
        // 删除后可能不是当前页，需要重新查询
        this.getqiyeList()
      }).catch(err => err)
    },
    // 查看企业
    chakan(id) {
      this.$router.push({
        path: '/exterpriseDetail',
        query: {
          id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}

.block {
  display: flex;
  justify-content: end;
}
</style>
